package com.ljx.comprehensiveCase.framework.beans.factory.xml;

import com.ljx.comprehensiveCase.framework.beans.BeanDefinition;
import com.ljx.comprehensiveCase.framework.beans.MultiplePropertyValues;
import com.ljx.comprehensiveCase.framework.beans.PropertyValue;
import com.ljx.comprehensiveCase.framework.beans.factory.support.BeanDefinitionReader;
import com.ljx.comprehensiveCase.framework.beans.factory.support.BeanDefinitionRegistry;
import com.ljx.comprehensiveCase.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 解析xml配置文件
 *
 * @作者 LJX
 * @日期 2022/12/27 16:30
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    private final BeanDefinitionRegistry beanDefinitionRegistry;

    public XmlBeanDefinitionReader(){
        beanDefinitionRegistry = new SimpleBeanDefinitionRegistry();
    }

    @Override
    public BeanDefinitionRegistry getRegistry() {
        return beanDefinitionRegistry;
    }

    /**
     * 加载配置文件并在注册表中进行注册
     * @param configLocation
     * @throws Exception
     */
    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        //获取输入流
        InputStream is = getClass().getClassLoader().getResourceAsStream(configLocation);

        //开始解析XML
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(is);
        Element rootElement = document.getRootElement();

        //解析bean
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            //获取id属性
            String id = element.attributeValue("id");
            //获取类名
            String aClass = element.attributeValue("class");
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(aClass);

            List<Element> property = element.elements("property");

            //创建PropertyValue迭代器
            MultiplePropertyValues propertyValues = new MultiplePropertyValues();

            for (Element e : property) {
                PropertyValue propertyValue = new PropertyValue(e.attributeValue("name"), e.attributeValue("ref"), e.attributeValue("value"));
                propertyValues.addPropertyValue(propertyValue);
            }

            //将迭代器添加到beanDefinition
            beanDefinition.setMultiplePropertyValues(propertyValues);
            //将beanDefinition注册到注册表
            beanDefinitionRegistry.registerBeanDefinition(beanDefinition.getId() , beanDefinition);

        }

    }
}
